﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using B10.Helpers;
using B10.Models;
using Microsoft.Security.Application;
using Telerik.Web.Mvc;
using System.Text.RegularExpressions;

namespace B10.Controllers
{
    [Authorize]
    [HandleError]
    public class ProfileController : Controller
    {
        IDatabaseRepository _db;

        public ProfileController()
            : this(new DatabaseRepository())
        {

        }

        public ProfileController(IDatabaseRepository db)
        {
            _db = db;
        }

        public ActionResult Index()
        {
            UserProfile profile = _db.GetProfile(UserHelper.UserId);

            if (profile == null)
                return new FileNotFoundResult();

            return View(new UserProfileFormViewModel(profile));
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Index(FormCollection collection)
        {
            UserProfile profile = _db.GetProfile(UserHelper.UserId);
            if (profile == null)
                return new FileNotFoundResult();
            UpdateModel(profile);
            profile.Email = Server.HtmlEncode(profile.Email);
            profile.GG = Server.HtmlEncode(profile.GG);
            profile.RealName = Server.HtmlEncode(profile.RealName);
            if (!String.IsNullOrEmpty(profile.RealName))
                profile.RealName = profile.RealName.Trim();
            profile.Skype = Server.HtmlEncode(profile.Skype);
            profile.Tagline = Server.HtmlEncode(profile.Tagline);
            profile.Website = Server.HtmlEncode(profile.Website);
            if (!String.IsNullOrEmpty(profile.Website) && !profile.Website.StartsWith("http"))
                profile.Website = "http://" + profile.Website;

            if (ModelState.IsValid)
            {
                if (collection.AllKeys.Contains("Content"))
                {
                    profile.Description = AntiXssHtmlHelper.GetSafeHtml(collection["Content"]);
                }
                if (Request.Files.Count == 1 && Request.Files[0].ContentLength > 0
                    && ImageHelper.IsCorrectContentType(Request.Files[0].ContentType))
                {
                    profile.Avatar = ImageHelper.SaveAvatar(Request.Files[0], User.Identity.Name);
                }
                _db.Save();
                return View(new UserProfileFormViewModel(profile, true));
            }
            return View(new UserProfileFormViewModel(profile));
        }

        #region adsense

        public ActionResult AdsenseSettings()
        {
            UserProfile profile = _db.GetProfile(UserHelper.UserId);

            if (profile == null)
                return new FileNotFoundResult();

            return View(profile);
        }

        [HttpPost]
        public ActionResult AdsenseSettings(FormCollection collection)
        {
            UserProfile profile = _db.GetProfile(UserHelper.UserId);
            if (profile == null)
                return View("Info", new InfoItem("Zapisywanie nie powiodło się. Spróbuj ponownie.", true));
            try
            {
                if (collection.AllKeys.Contains("AdsenseCode"))
                {
                    string code = collection["AdsenseCode"];
                    if (!String.IsNullOrEmpty(code))
                    {
                        code = code.Trim();
                        if (!String.IsNullOrEmpty(code) && Regex.IsMatch(code,
                            @"^pub\-\d+$"))
                        {
                            profile.AdsenseCode = Server.HtmlEncode(code);
                            if (ModelState.IsValid)
                            {
                                _db.Save();
                                return View("Info", new InfoItem("Gotowe!"));
                            }
                        }
                        else
                        {
                            return View("Info", new InfoItem(
                                "Nieprawidłowy identyfikator google adsense.", true));
                        }
                    }
                }
                return View("Info", new InfoItem("Zapisywanie nie powiodło się. Spróbuj ponownie.", true));

            }
            catch
            {
                return View("Info", new InfoItem("Zapisywanie nie powiodło się. Spróbuj ponownie.", true));
            }
        }

        #endregion

        #region page list

        public ActionResult PageList()
        {
            return View();
        }

        [GridAction]
        public ActionResult _PageList()
        {
            if (!Request.IsAuthenticated)
                return new ForbiddenResult();
            _db.LazyLoading = false;
            var pages = _db.GetAllPages();

            pages = pages.Where(p => p.ProfileId == UserHelper.UserId);
            return View(new GridModel<UserPage>()
            {
                Data = pages
            });
        }

        //public ActionResult Pages(int sidx, string sord, int page, int rows)
        //{
        //    if (!Request.IsAuthenticated)
        //        return new ForbiddenResult();

        //    var pages = _db.GetAllPages();

        //    pages = pages.Where(p => p.OwnerName == User.Identity.Name);

        //    switch (sidx)
        //    {
        //        case 0: pages =
        //            sord == "asc" ? pages.OrderBy(p => p.Title) :
        //                pages.OrderByDescending(p => p.Title);
        //            break;
        //        case 1:
        //            pages = sord == "asc" ? pages.OrderBy(p => p.CreatedDate) :
        //                pages.OrderByDescending(p => p.CreatedDate);
        //            break;
        //    }

        //    var paginated = new PaginatedList<UserPage>(pages, page, rows);

        //    var jsonData = new
        //    {
        //        total = paginated.ListInfo.TotalPages,
        //        page = page,
        //        records = paginated.ListInfo.TotalCount,
        //        rows = (
        //          from p in paginated
        //          select new
        //          {
        //              id = p.Id,
        //              cell = new string[] {
        //                String.Format("<div><a href='{0}' title='{1}'>{2}</a></div>",Url.Action("Page","Home",new {pageUrl = p.Url,id=p.Id}),p.Title,
        //                String.IsNullOrEmpty(p.Title) || p.Title.Length < 40 ? p.Title : p.Title.Substring(0,40) + "..."),
        //                p.CreatedDate.ToShortDateString(),
        //                p.Status == PageStatus.Accepted ?
        //                "" :
        //                String.Format("<a href='{0}'>Edytuj</a>",Url.Action("Edit","Page",new {id = p.Id})),
        //                p.Status == PageStatus.Accepted ?
        //                "" :
        //                String.Format("<a href='#' onclick='askDelete({0});return false;'>Usuń</a>",p.Id)
        //              }
        //          }).ToArray()
        //    };
        //    return Json(jsonData);

        //}

        #endregion

    }
}
